//
//  MessageController.m
//  HarmonizePub
//
//  Created by rzhy on 2016/10/31.
//  Copyright © 2016年 Zy. All rights reserved.
//

#import "MessageController.h"
#import "Config.h"
#import <UIScrollView+EmptyDataSet.h>
#import "MessageTableViewCell.h"
#import "WebViewController.h"

static NSString *CellIdentifier = @"Cell";

@interface MessageController () <UITableViewDataSource, UITableViewDelegate, DZNEmptyDataSetSource, DZNEmptyDataSetDelegate>
{
    NSMutableArray *_dataArrayM;
}
@property (weak, nonatomic) IBOutlet UITableView *tableView;

@end

@implementation MessageController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.tableView.tableFooterView = [[UIView alloc] initWithFrame:CGRectZero];
    self.tableView.emptyDataSetSource = self;
    self.tableView.emptyDataSetDelegate = self;
    UINib *nib = [UINib nibWithNibName:[MessageTableViewCell registerName] bundle:nil];
    [self.tableView registerNib:nib forCellReuseIdentifier:CellIdentifier];
}

- (void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];
    [self getMsgList];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - 我的消息列表
- (void)getMsgList {
    NSDictionary *cookie = @{CookieVaule : [UserDefaultsTool stringForKey:XHToken]};
    [HTTPSTool POSTRequestWithPath:XHGetMsgList cookie:cookie params:nil success:^(NSDictionary * _Nonnull JSON) {
//        XHLog(@"我的消息列表 -> JSON: %@", JSON)
        _dataArrayM = [JSON[@"data"][@"list"] mutableCopy];
        [_tableView reloadData];
        NSInteger count = [JSON[@"data"][@"count"] integerValue];
        [UIApplication sharedApplication].applicationIconBadgeNumber = count;
        [UserDefaultsTool setObject:@(count) forKey:XHNewMessage];
        [[NSNotificationCenter defaultCenter] postNotificationName:XHNewMessage object:nil userInfo:nil];
    }];
}

#pragma mark - tableView delegate/dataSource Method
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return _dataArrayM.count;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return [MessageTableViewCell cellHeight];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    MessageTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    NSDictionary *dataDict = _dataArrayM[indexPath.row];
    cell.isRead = [dataDict[@"isRead"] boolValue];
    [cell setCellShowDataWithDataDictionary:dataDict];
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    [tableView deselectRowAtIndexPath:indexPath animated:NO];
    NSDictionary *dataDict = _dataArrayM[indexPath.row];
    [self readMsgWithDataDictionary:dataDict];
//    XHLog(@"%@", dataDict)
    NSString *typeValue = dataDict[@"typeValue"];
    NSString *remark = dataDict[@"remark"];
    if ([typeValue isEqualToString:@"webview"]) {
        // WebView
        WebViewController *webView = [[WebViewController alloc] init];
        webView.title = dataDict[@"title"];
        webView.url = [URLTool webURLStringWithPathString:remark token:[UserDefaultsTool stringForKey:XHToken]];
        [self.navigationController pushViewController:webView animated:YES];
    } else {
        [self setAlertViewWithMessage:@"暂时无法查看详情，静待更新！"];
    }
}

- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
    return YES;
}

- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
    if (editingStyle == UITableViewCellEditingStyleDelete) {
        // 删除
        NSDictionary *dataDict = _dataArrayM[indexPath.row];
        NSDictionary *cookie = @{CookieVaule : [UserDefaultsTool stringForKey:XHToken]};
        NSDictionary * param = @{@"id" : dataDict[@"id"]};
        [HTTPSTool POSTRequestWithPath:XHDelMsg cookie:cookie params:param success:^(NSDictionary * _Nonnull JSON) {
            [_dataArrayM removeObject:dataDict];
            [tableView deleteRowsAtIndexPaths:[NSMutableArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationAutomatic];
            if (![dataDict[@"isRead"] boolValue]) {
                NSInteger count = [UserDefaultsTool integerForKey:XHNewMessage];
                if (count) {
                    [UserDefaultsTool setObject:@(count - 1) forKey:XHNewMessage];
                    [UIApplication sharedApplication].applicationIconBadgeNumber = count - 1;
                    [[NSNotificationCenter defaultCenter] postNotificationName:XHNewMessage object:nil userInfo:nil];
                }
            }
        }];
    }
}

#pragma mark - 消息已读回执
- (void)readMsgWithDataDictionary:(NSDictionary *)dataDict {
    NSDictionary *cookie = @{CookieVaule : [UserDefaultsTool stringForKey:XHToken]};
    NSDictionary *param = @{@"id" : dataDict[@"id"]};
    [HTTPSTool POSTRequestHidenHUDWithPath:XHReadMsg cookie:cookie params:param progress:nil success:^(NSDictionary * _Nonnull JSON) {
//        XHLog(@"消息已读回执 -> JSON: %@", JSON)
    } failure:nil];
}

- (void)setAlertViewWithMessage:(NSString *)message {
    UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"提 示:" message:message preferredStyle:UIAlertControllerStyleAlert];
    UIAlertAction *defaultAction = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:nil];
    [alertController addAction:defaultAction];
    [self presentViewController:alertController animated:YES completion:nil];
}

#pragma mark - DZNEmptyDataSetSource Method
- (UIImage *)imageForEmptyDataSet:(UIScrollView *)scrollView {
    UIImage *image = [UIImage imageNamed:@"LoadFailure.png"];
    return image;
}

- (NSAttributedString *)descriptionForEmptyDataSet:(UIScrollView *)scrollView {
    NSString *string = XHEmptyDes;
    NSAttributedString *abs = [[NSAttributedString alloc] initWithString:string attributes:nil];
    return abs;
}

- (CGFloat)verticalOffsetForEmptyDataSet:(UIScrollView *)scrollView {
    return -64.0f;
}

#pragma mark - DZNEmptyDataSetDelegate Method
- (BOOL)emptyDataSetShouldDisplay:(UIScrollView *)scrollView {
    return YES;
}

- (BOOL)emptyDataSetShouldAllowTouch:(UIScrollView *)scrollView {
    return YES;
}

- (BOOL)emptyDataSetShouldAllowScroll:(UIScrollView *)scrollView {
    return YES;
}

- (void)emptyDataSet:(UIScrollView *)scrollView didTapView:(UIView *)view {
    [self getMsgList];
}

@end
